package offer.zixing.chapter15;

import java.util.LinkedList;
import java.util.Queue;

public class Test107 {
    public static void main(String[] args) {
        int[][] matrix = {{0,0,0}, {0,1,0}, {1,1,1}};
        print(updateMatrix(matrix));
    }

    private static int[][] updateMatrix(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] res = new int[rows][cols];
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    res[i][j] = 0;
                    queue.add(new int[]{i, j});
                } else {
                    res[i][j] = Integer.MAX_VALUE;
                }
            }
        }
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        while (!queue.isEmpty()) {
            int[] temp = queue.poll();
            int dist = res[temp[0]][temp[1]];
            for (int[] dir : dirs) {
                int r = temp[0] + dir[0];
                int c = temp[1] + dir[1];
                if (r >= 0 && r < rows && c >= 0 && c < cols) {
                    if (res[r][c] > dist + 1) {
                        res[r][c] = dist + 1;
                        queue.add(new int[]{r, c});
                    }
                }
            }
        }
        return res;
    }

    private static void print(int[][] res) {
        for (int[] row : res) {
            for (int v : row) {
                System.out.print(v + " ");
            }
            System.out.println();
        }
    }
}
